"""
    Software : PyCharm
    File     : validators.py
    Time     : 2021/6/2 21:47
    Author   : Pontoon
    describe :
"""
import ast
from django.core.exceptions import ValidationError
from rest_framework import serializers
from rest_framework.exceptions import ValidationError

from projects.userprofile.models import UserProfile
from .models import Group, GroupMessage


class GroupValidate(serializers.ModelSerializer):
    creator = serializers.CharField(required=True)
    member = serializers.CharField()

    class Meta:
        model = Group
        fields = ["creator", "member", "name"]

    def validate_creator(self, data):
        creator_obj = UserProfile.objects.filter(uid=data).first()
        if creator_obj:
            return data
        raise ValidationError("非法请求参数")

    def validate_member(self, data):
        member_list = ast.literal_eval(data)
        try:
            UserProfile.objects.in_bulk(member_list)
        except ValidationError:
            raise ValidationError("非法请求参数")
        return data

    def create(self, validated_data):
        name = validated_data.get("name")
        creator = validated_data.get("creator")
        member = validated_data.get("member")
        member_list = ast.literal_eval(member)
        group = Group.objects.create(creator_id=creator, name=name)
        group.member.add(*member_list)
        return group


class GroupMessageValidate(serializers.ModelSerializer):
    group = serializers.PrimaryKeyRelatedField(queryset=Group.objects)
    user = serializers.PrimaryKeyRelatedField(queryset=UserProfile.objects)

    class Meta:
        model = GroupMessage
        fields = ["group", "user", "message"]
